<!-- 人口统计学信息 一般信息 generalInformation-->
<template>
  <div class="page-center">
    <div class="medical-form">
      <!-- 病人标识信息 -->
      <div class="patient-info-header">
        <div class="info-left">
          <p>住院病案首页内容预览(注意打印前仔细核对内容!)</p>
          <p>温州医科大学附属第一医院</p>
        </div>
        <div class="info-right">
          <span>组织机构代码 47000592</span>
          <span>病案号 {{ display(patientDisplay.medicalRecordNumber) }}</span>
        </div>
      </div>

      <!-- 就诊信息：表单样式展示 -->
      <div class="visit-info">
        <el-form :model="admissionDisplay" label-width="120px" class="info-form" label-position="right">
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="医疗付费方式">
                <div class="display-value">{{ display(admissionDisplay.admissionPayment) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门诊号">
                <div class="display-value">{{ display(admissionDisplay.outpatientNumber) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="住院次数">
                <div class="display-value">{{ display(admissionDisplay.admissionTimes) }}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 病人基本信息：表单样式展示 -->
      <div class="patient-info">
        <el-divider content-position="left">
          <h3>病人基本信息</h3>
        </el-divider>

        <el-form :model="patientDisplay" label-width="120px" class="info-form" label-position="right">
          <!-- 基本信息展示保持不变 -->
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="姓名">
                <div class="display-value info-value">{{ display(patientDisplay.name) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别">
                <div class="display-value info-value">{{ display(patientDisplay.gender) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出生日期">
                <div class="display-value info-value">{{ display(formatDate(patientDisplay.birthDate)) }}</div>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="年龄">
                <div class="display-value info-value">{{ display(patientDisplay.age ? patientDisplay.age + '岁' : null) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="国籍">
                <div class="display-value info-value">{{ display(patientDisplay.nationality) }}</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="出生地">
                <div class="display-value info-value">{{ display(patientDisplay.birthPlace) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="籍贯">
                <div class="display-value info-value">{{ display(patientDisplay.nativePlace) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="民族">
                <div class="display-value info-value">{{ display(patientDisplay.ethnicity) }}</div>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="身份证号">
                <div class="display-value info-value">{{ display(patientDisplay.idNumber) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="职业">
                <div class="display-value info-value">{{ display(patientDisplay.occupation) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="婚姻">
                <div class="display-value info-value">{{ display(patientDisplay.maritalStatus) }}</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="现住址">
                <div class="display-value info-value">{{ display(patientDisplay.address) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="电话">
                <div class="display-value info-value">{{ display(patientDisplay.phone) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="邮编">
                <div class="display-value info-value">{{ display(patientDisplay.postalCode) }}</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="户口地址">
                <div class="display-value info-value">{{ display(patientDisplay.registerAddress) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="户口邮编">
                <div class="display-value info-value">{{ display(patientDisplay.registerPostalCode) }}</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="工作单位及地址">
                <div class="display-value info-value">{{ display(patientDisplay.workUnit) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单位电话">
                <div class="display-value info-value">{{ display(patientDisplay.workPhone) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单位邮编">
                <div class="display-value info-value">{{ display(patientDisplay.workPostalCode) }}</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="联系人姓名">
                <div class="display-value info-value">{{ display(patientDisplay.contactName) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关系">
                <div class="display-value info-value">{{ display(patientDisplay.contactRelation) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人电话">
                <div class="display-value info-value">{{ display(patientDisplay.contactPhone) }}</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="12">
            <el-col :span="24">
              <el-form-item label="联系人地址">
                <div class="display-value info-value">{{ display(patientDisplay.contactAddress) }}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 入院出院信息（保留表格/只读表单风格） -->
      <div class="admission-info">
        <el-form :model="admissionDisplay" label-width="120px" class="info-form" label-position="right">
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="入院途径">
                <div class="display-value info-value">{{ display(admissionDisplay.admissionRoute) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入院时间">
                <div class="display-value info-value">{{ display(formatDate(admissionDisplay.admissionTime)) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入院科别">
                <div class="display-value info-value">{{ display(admissionDisplay.admissionDept) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="病房">
                <div class="display-value info-value">{{ display(admissionDisplay.ward) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="转科科别">
                <div class="display-value info-value">{{ display(admissionDisplay.transferDept) }}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-row :gutter="10">
          <el-col :span="8">
            <span>出院时间：</span>
            <span class="info-value display-value">2023-07-31</span>
          </el-col>
          <el-col :span="8">
            <span>出院科别：</span>
            <span class="info-value display-value">泌尿外科</span>
          </el-col>
          <el-col :span="8">
            <span>病房：</span>
            <span class="info-value display-value">14病区 009</span>
          </el-col>
          <el-col :span="8">
            <span>实际住院：</span>
            <span class="info-value display-value">1 天</span>
          </el-col>
        </el-row>
      </div>

      <!-- 病人医疗情况保持原表格，顶部用表单样式展示关键信息 -->
      <div class="medical-info">
        <el-divider content-position="left">
          <h3>病人医疗情况</h3>
        </el-divider>

        <el-form :model="medicalDisplay" label-width="120px" class="info-form" label-position="right">
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="门(急)诊诊断">
                <div class="display-value info-value">{{ display(medicalDisplay.clinicDiagnosis) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="疾病编码">
                <div class="display-value info-value">{{ display(medicalDisplay.code) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="确诊日期">
                <div class="display-value info-value">{{ display(formatDate(medicalDisplay.diagnosisDate)) }}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 出院诊断表格（按接口渲染 diagnosisDetails） -->
        <h3>诊断明细</h3>
        <el-table v-if="diagnosisDetails && diagnosisDetails.length" :data="diagnosisDetails" border style="width: 100%">
          <el-table-column prop="type" label="类型" width="80">
            <template slot-scope="scope">{{ scope.row.type === 1 ? '主要' : '次要' }}</template>
          </el-table-column>
          <el-table-column prop="diagnosis" label="诊断名称" min-width="240" />
          <el-table-column prop="diagnosisCode" label="诊断编码" width="140" />
          <el-table-column prop="hospital" label="就诊机构" min-width="200" />
        </el-table>

        <h3 style="margin-top:16px">手术明细</h3>
        <el-table v-if="surgeryDetails && surgeryDetails.length" :data="surgeryDetails" border style="width: 100%">
          <el-table-column prop="surgeryOperationDate" label="手术日期" width="160">
            <template slot-scope="scope">{{ formatDate(scope.row.surgeryOperationDate) }}</template>
          </el-table-column>
          <el-table-column prop="surgeryOperationName" label="手术名称" min-width="240" />
          <el-table-column prop="surgeryOperationCode" label="手术编码" width="140" />
          <el-table-column prop="surgeon" label="主刀医师" width="140" />
          <el-table-column prop="anesthesiaMethod" label="麻醉方式" width="140" />
          <el-table-column prop="incisionHealingGrade" label="切口愈合等级" width="140" />
        </el-table>

        <el-row>
          <el-col :span="24">
            <p>入院病情：1，有，2，临床未确定，3，情况不明，4，无</p>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <span>损伤、中毒的外部原因</span>
            <span class="info-value">-</span>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { details } from '@/api/dataEntry/demographicInformation'

export default {
  name: 'MedicalRecordPage',
  data() {
    return {
      diagnosisDetails: [],
      surgeryDetails: [],
      patientDisplay: {},
      admissionDisplay: {},
      medicalDisplay: {},
      loading: false
    }
  },
  computed: {
    ...mapGetters('patient', ['robustPatientId', 'patientFallbackData'])
  },
  watch: {
    robustPatientId: {
      handler(newId) {
        if (newId) {
          this.loadPatientData(newId)
        } else {
          this.resetDisplayData()
        }
      },
      immediate: true
    }
  },
  async mounted() {
    if (!this.robustPatientId) {
      const restored = await this.restorePatientFromStorage()
      if (restored) {
        this.loadPatientData(restored.id || restored.patientId)
      }
    }
  },
  methods: {
    ...mapActions('patient', ['restorePatientFromStorage']),

    async loadPatientData(id) {
      if (this.loading) return

      this.loading = true
      try {
        const response = await details({ recordId: id })
        this.handleResponseData(response)
      } catch (error) {
        console.error('获取患者一般信息失败:', error)
        this.applyFallbackData()
      } finally {
        this.loading = false
      }
    },

    handleResponseData(response) {
      const payload = response?.data?.data ?? response?.data ?? response ?? {}

      if (payload) {
        this.syncDisplayFromPatient(payload)
        this.diagnosisDetails = payload.diagnosisDetails || []
        this.surgeryDetails = payload.surgeryDetails || []
      }
    },

    syncDisplayFromPatient(patient) {
      // 优化字段映射逻辑
      this.patientDisplay = {
        medicalRecordNumber: patient.medicalRecordNumber || patient.number || '',
        name: patient.name || patient.patientName || '',
        gender: patient.gender || '',
        birthDate: patient.birthDate || '',
        age: patient.age || '',
        nationality: patient.nationality || '',
        birthPlace: patient.birthPlace || '',
        nativePlace: patient.origin || patient.nativePlace || '',
        ethnicity: patient.ethnicity || '',
        idNumber: patient.idNumber || '',
        occupation: patient.job || patient.occupation || '',
        maritalStatus: patient.marryStatus || patient.maritalStatus || '',
        address: patient.currentAddress || patient.address || '',
        phone: patient.phone || '',
        postalCode: patient.currentAddressZip || patient.postalCode || '',
        registerAddress: patient.registrationAddress || '',
        registerPostalCode: patient.registrationAddressZip || '',
        workUnit: patient.workPlace || '',
        workPhone: patient.workPlacePhone || '',
        workPostalCode: patient.workPlaceZip || '',
        contactName: patient.contact || '',
        contactRelation: patient.relationship || '',
        contactAddress: patient.contactAddress || '',
        contactPhone: patient.contactPhone || ''
      }

      this.admissionDisplay = {
        admissionPayment: patient.admissionPayment || '',
        outpatientNumber: patient.outpatientNumber || '',
        admissionTimes: patient.admissionTimes || '',
        admissionRoute: patient.admissionRoute || '',
        admissionTime: patient.admissionTime || '',
        admissionDept: patient.admissionDepartment || '',
        ward: patient.ward || '',
        transferDept: patient.transferDepartment || ''
      }

      this.medicalDisplay = {
        clinicDiagnosis: patient.diagnosis || (patient.diagnosisDetails?.find(d => d.type === 1)?.diagnosis || ''),
        code: patient.diagnosisCode || (patient.diagnosisDetails?.find(d => d.type === 1)?.diagnosisCode || ''),
        diagnosisDate: patient.dateTime || patient.diagnosisDate || ''
      }
    },

    applyFallbackData() {
      const patient = this.patientFallbackData
      if (patient) {
        this.syncDisplayFromPatient(patient)
      }
    },

    resetDisplayData() {
      this.diagnosisDetails = []
      this.surgeryDetails = []
      this.patientDisplay = {}
      this.admissionDisplay = {}
      this.medicalDisplay = {}
    },

    display(val) {
      if (val === null || val === undefined || String(val).trim() === '') return '-'
      return val
    },

    formatDate(dt) {
      if (!dt) return '-'
      return String(dt).replace('T', ' ').replace(/\.\d+$/, '')
    }
  }
}
</script>

<!-- 引入共享样式 -->
<style src="@/styles/shared.css"></style>

<style scoped>
.patient-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 14px 18px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  background-color: #fafafa;
  box-sizing: border-box;
}

.patient-info-header .info-right {
  text-align: right;
  display: flex;
  gap: 12px;
  align-items: center;
}

.patient-info-header .info-left p {
  margin: 0;
  line-height: 1.4;
}
</style>
